import React, { useEffect, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  Select,
  Button,
  Table,
  Input,
  message,
  Upload,
  Tree,
  TreeSelect,
  Modal,
} from "antd";
import {
  PlusOutlined,
  ExclamationCircleFilled,
  DeleteOutlined,
  SearchOutlined,
  UploadOutlined,
  EditOutlined,
} from "@ant-design/icons";
import {
  text_check,
  post_axios,
  key_find_check_value,
  box_type_list,
} from "../../utils";

export default function K12WxStudent(props) {
  const { t } = useTranslation();
  const [tableHeight, setTableHeight] = useState(0);
  const { actions, setSpinning } = props;
  const { Option } = Select;
  const { confirm } = Modal;
  let { menu_action, user_power_lang, username, user_grade } = actions;
  user_power_lang = JSON.parse(user_power_lang);

  // 国内国外判断
  const session_company = sessionStorage.getItem("company");
  let localStorage_company = JSON.parse(localStorage.getItem("choose_company"));
  const local_company_object =
    localStorage_company &&
    localStorage_company[username] &&
    localStorage_company[username]
      ? localStorage_company[username]
      : "";

  const user_type_list = {
    STUDENT: {
      msg_en: "student",
      msg_cn: "学生",
    },
    STAFF: {
      msg_en: "staff",
      msg_cn: "职工",
    },
  };

  // 公司范围
  const [company_scope, setCompany_scope] = useState("now");
  // 机构
  const [organization_ids, setOrganization_ids] = useState("");
  // 年级
  const [org_class_id, setOrg_class_id] = useState("");
  // 手机号
  const [parent_tel, setParent_tel] = useState("");
  // 姓名
  const [name, setName] = useState("");
  const [data_list, setData_list] = useState([]);
  const [page, setPage] = useState(1);
  const [rows, setRows] = useState(20);
  const [total, setTotal] = useState(0);

  const getData = async (newPage, newRows) => {
    let upMsg = {
      page: newPage ? newPage : page,
      rows: newRows ? newRows : rows,
      company_id: company_scope == "now" ? local_company_object.id : "",
      company: company_scope == "now" ? local_company_object.company : "",
      organization_ids: organization_ids,
      org_class_id: org_class_id,
      parent_tel: parent_tel,
      name: name,
    };
    setSpinning(true);
    let res = await post_axios("k12_wx_student", "m_query", upMsg);
    setSpinning(false);
    if (!res) return;
    setData_list(res.data_rows.rows);
    setTotal(res.data_rows.total);
  };
  const columns = [
    {
      dataIndex: "idx",
      align: "center",
      width: 40,
      render: (_, record, index) => <>{index + 1}</>,
    },
    {
      title: "姓名",
      dataIndex: "user_name",
      align: "center",
    },
    {
      title: "年级",
      dataIndex: "org_class",
      align: "center",
    },
    {
      title: "类型",
      align: "center",
      render: (_, record, index) => (
        <>{text_check(user_type_list[record.user_type])}</>
      ),
    },
    {
      title: "状态",
      align: "center",
      render: (_, record, index) => (
        <>{record.status == "NORMAL" ? <span>正常</span> : <span>禁用</span>}</>
      ),
    },
    {
      title: "签约状态",
      align: "center",
      render: (_, record, index) => (
        <>
          {record.contract_state == "NOT_CONTRACTED" ? (
            <span>未签约</span>
          ) : record.contract_state == "TERMINATED" ? (
            <span>已解约</span>
          ) : (
            <span>已签约</span>
          )}{" "}
        </>
      ),
    },
    {
      title: "采集人脸",
      align: "center",
      render: (_, record, index) => (
        <>{record.face_image_ok == "YES" ? <span>已采集</span> : <span>未采集</span>}</>
      ),
    },
    {
      title: "协议号",
      dataIndex: "contract_id",
      align: "center",
    },
    {
      title: "协议号",
      dataIndex: "parent_tel",
      align: "center",
    },
    {
      title: "机构名称",
      dataIndex: "organization_name",
      align: "center",
    },
  ];

  // 分页器
  const pageOnChange = async (page, pageSize) => {
    setPage(page);
    setRows(pageSize);
    initData(page, pageSize);
  };

  const search_data = () => {
    setPage(1);
    initData();
  };

  const initData = () => {
    getData();
  };

  const search_organization_change = (val) => {
    setOrganization_ids(val);
    if (val.length === 1) {
      search_class_data(val);
    } else {
      setSearch_class_data_list("");
    }
  };
  const [search_class_data_list, setSearch_class_data_list] = useState();
  const search_class_data = async (value) => {
    let upMsg = {
      organization_id: value[0],
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("k12_wx_organization", "m_query_class", upMsg);
    if (!res) return;
    setSearch_class_data_list(res.data_rows.rows);
  };
  const [school_organization_data_list, setSchool_organization_data_list] =
    useState("");
  const get_school_organization_data = async () => {
    let upMsg = {
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("k12_wx_organization", "m_query", upMsg);
    if (!res) return;
    setSchool_organization_data_list(res.data_rows.rows);
  };
  const organizationOnChange = (value) => {
    setOrganization_id(value);
    get_class_data(value);
  };
  const [class_data_list, setClass_data_list] = useState();
  const get_class_data = async (organization_id) => {
    let upMsg = {
      organization_id,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let res = await post_axios("k12_wx_organization", "m_query_class", upMsg);
    if (!res) return;
    setClass_data_list(res.data_rows.rows);
  };

  // 编辑学生
  const [edit_student_show, setEdit_student_show] = useState(false);
  const [edit_student_title, setEdit_student_title] = useState();
  const [edit_type, setEdit_type] = useState("add");

  const [organization_id, setOrganization_id] = useState("");
  const [user_name, setUser_name] = useState("");
  const [edit_org_class_id, setEdit_org_class_id] = useState("");
  const [user_parent_tel, setUser_parent_tel] = useState("");
  const [user_remark, setUser_remark] = useState("");
  const edit_student_dialog_show = (value) => {
    setEdit_type(value);
    if (value === "add") {
      setEdit_student_title(t("common.add"));
      setOrganization_id("");
      setUser_name("");
      setEdit_org_class_id("");
      setUser_parent_tel("");
      setUser_remark("");

      setEdit_student_show(true);
    } else {
      setEdit_student_show(true);
    }
  };
  const edit_student_confirm = async () => {
    if (organization_id === 0) {
      message.warning({
        content: "请选择机构",
      });
      return;
    }

    if (user_name === "") {
      message.warning({
        content: "请输入姓名",
      });
      return;
    }
    if (edit_org_class_id === "") {
      message.warning({
        content: "请选择年级",
      });
      return;
    }
    if (user_parent_tel === "") {
      message.warning({
        content: "请输入家长手机号",
      });
      return;
    }

    let upMsg = {
      organization_id: organization_id,
      user_name: user_name,
      org_class_id: edit_org_class_id,
      parent_tel: user_parent_tel,
      user_remark: user_remark,
      company_id: local_company_object.id,
      company: local_company_object.company,
    };
    let action = "m_add";
    if (edit_type === "change") {
      action = "m_modify";
    }
    setSpinning(true);
    let res = await post_axios("k12_wx_student", action, upMsg);
    setSpinning(false);
    if (!res) return;
    message.success({
      content: t("common.successfully"),
    });
    setEdit_student_show(false);
    search_data();
  };

  useEffect(() => {
    // 挂载后或者更新后的操作
    getData().then(() => {
      const tabBoxHeight =
        document.getElementsByClassName("k12_wx_student")[0].scrollHeight;
      const tableHeight = tabBoxHeight - 96 - 70;
      setTableHeight(tableHeight);
      get_school_organization_data();
    });
  }, []);
  return (
    <>
      <div className="k12_wx_student modules">
        <div className="screen_ipt">
          {user_grade < 10 ? (
            <div className="ipt_box short_title">
              <div className="ipt_box_title">{t("system_manager.company")}</div>
              <Select
                size="small"
                placeholder=" "
                options={[
                  {
                    label: t("system_manager.current_selected"),
                    value: "now",
                    key: "now",
                  },
                  {
                    label: t("system_manager.all"),
                    value: "*",
                    key: "*",
                  },
                ]}
                value={company_scope}
                onChange={(value) => setCompany_scope(value)}
              />
            </div>
          ) : (
            ""
          )}
          <div className="ipt_box short_title">
            <div className="ipt_box_title">手机号</div>
            <Input
              placeholder=" "
              size="small"
              value={parent_tel}
              onChange={(e) => setParent_tel(e.target.value)}
            />
          </div>
          <div className="ipt_box short_title">
            <div className="ipt_box_title">姓名</div>
            <Input
              placeholder=" "
              size="small"
              value={name}
              onChange={(e) => setName(e.target.value)}
            />
          </div>
          <div className="ipt_box short_title">
            <div className="ipt_box_title">机构</div>
            <Select
              type="multiple"
              placeholder=" "
              size="small"
              value={organization_ids}
              onChange={search_organization_change}
              options={school_organization_data_list}
              fieldNames={{
                label: "organization_name",
                value: "organization_id",
              }}
            />
          </div>
          <div className="ipt_box short_title">
            <div className="ipt_box_title">年级</div>
            <Select
              placeholder=" "
              size="small"
              value={org_class_id}
              onChange={(value) => setOrg_class_id(value)}
              options={search_class_data_list}
              fieldNames={{
                label: "org_class",
                value: "org_class_id",
              }}
            />
          </div>
        </div>
        <div className="screen_btn">
          <div className="btn_box">
            {/* 添加 */}
            {menu_action.indexOf("m_add") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<PlusOutlined style={{ color: "#1677FF" }} />}
                onClick={() => edit_student_dialog_show("add")}
              >
                {text_check(user_power_lang["m_add"])}
              </Button>
            ) : (
              ""
            )}
            {/* 修改 */}
            {menu_action.indexOf("m_modify") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<EditOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_modify"])}
              </Button>
            ) : (
              ""
            )}
            {/* 删除 */}
            {menu_action.indexOf("m_del") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<DeleteOutlined style={{ color: "#1677FF" }} />}
              >
                {text_check(user_power_lang["m_del"])}
              </Button>
            ) : (
              ""
            )}
            {/* 查询 */}
            {menu_action.indexOf("m_query") > -1 ? (
              <Button
                size="small"
                type="text"
                icon={<SearchOutlined style={{ color: "#1677FF" }} />}
                onClick={search_data}
              >
                {text_check(user_power_lang["m_query"])}
              </Button>
            ) : (
              ""
            )}
          </div>
        </div>
        <div className="table_box">
          <div
            className="page-table"
            style={{
              width: "100vw",
            }}
          >
            <Table
              dataSource={data_list}
              size="small"
              bordered
              columns={columns}
              rowKey="organization_id"
              virtual
              scroll={{
                y: tableHeight,
              }}
              rowHoverable={false}
              pagination={{
                defaultCurrent: page,
                defaultPageSize: rows,
                size: "small",
                current: page,
                total: total,
                responsive: true,
                showTotal: (total) =>
                  text_check({
                    msg_cn: `共 ${total} 条`,
                    msg_en: `Total ${total} items`,
                  }),
                onChange: pageOnChange,
              }}
            />
          </div>
        </div>
      </div>

      <Modal
        title={edit_student_title}
        open={edit_student_show}
        onOk={edit_student_confirm}
        onCancel={() => setEdit_student_show(false)}
        classNames={{ body: "edit_dialog_body" }}
        maskClosable={false}
        destroyOnClose={true}
      >
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">机构</div>
          <Select
            placeholder=" "
            size="small"
            value={organization_id}
            onChange={organizationOnChange}
            options={school_organization_data_list}
            fieldNames={{
              label: "organization_name",
              value: "organization_id",
            }}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">年级</div>
          <Select
            placeholder=" "
            size="small"
            value={edit_org_class_id}
            onChange={(value) => setEdit_org_class_id(value)}
            options={class_data_list}
            fieldNames={{
              label: "org_class",
              value: "org_class_id",
            }}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">姓名</div>
          <Input
            placeholder=" "
            size="small"
            value={user_name}
            onChange={(e) => setUser_name(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">手机号</div>
          <Input
            placeholder=" "
            size="small"
            value={user_parent_tel}
            onChange={(e) => setUser_parent_tel(e.target.value)}
          />
        </div>
        <div className="dialog_ipt_box">
          <div className="ipt_box_title">备注</div>
          <Input
            placeholder=" "
            value={user_remark}
            onChange={(e) => setUser_remark(e.target.value)}
          />
        </div>
      </Modal>
    </>
  );
}
